package com.example.webmodule.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.example.webmodule.entity.ServiceInfo;
import com.example.webmodule.strategy.RegistrySelectStrategy;
import com.example.webmodule.strategy.RegistryStrategyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Properties;

@RestController
@RequestMapping("/web/nacos")
public class NacosController {
//    @GetMapping("/getNacosData")
//    public String getNacosData() throws NacosException {
//        Properties properties = new Properties();
//        properties.setProperty("serverAddr", "http://127.0.0.1:8848");
//        properties.setProperty("namespace", "csdc");
////        properties.setProperty("groupName", "default");
//        NamingService namingService = NacosFactory.createNamingService(properties);
//        List<String> serverList = namingService.getServicesOfServer(
//                1, Integer.MAX_VALUE, "default").getData();
//        for (String serviceName : serverList) {
//            System.out.println(serviceName);
//            List<Instance> instanceList = namingService.getAllInstances(serviceName, "default");
//            for (Instance instance: instanceList) {
//                System.out.println(JSON.toJSONString(instance));
//            }
//        }
//        // ["module-a","module-b"]
//
//        return JSON.toJSONString(serverList);
//    }
//
    @Autowired
    private RegistryStrategyFactory registryStrategyFactory;
//
    @GetMapping("/getNacosData/v2")
    public String getNacosData2() throws Exception {
        RegistrySelectStrategy registrySelectStrategy = registryStrategyFactory.getStrategy();
        List<String> serverList = registryStrategyFactory.getStrategy().getServices();
        for (String serviceName : serverList) {
            System.out.println(serviceName);
            List<ServiceInfo> instanceList = registrySelectStrategy.getServiceInstances(serviceName);
            System.out.println(JSON.toJSONString(instanceList));
        }
        // ["module-a","module-b"]
        return JSON.toJSONString(serverList);
    }
}
